#!/usr/bin/python
'''
init the package table in db with the specified os_release and build,
note that all packages in db of the os_release you give will be cleared,
and obsoleted and renamed packages in initial build will be ignored.
command:
./manage.py init_pkg_db --os_release s11u2 --build 04
./manage.py init_pkg_db -o s11u2 -b 04
'''

import os
import sys
import subprocess
from datetime import datetime

from django.core.management.base import BaseCommand, CommandError
from package.models import Module, PackageName, Package, FixedBug, ChangedPackage, Dependancy, OSRelease
from package import const
import util

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('-o',
            '--'+util.OS_RELEASE,
            action='store',
            type='string',
            dest=util.OS_RELEASE,
            help='designate the os release. eg. \'s11u2\' or \'s12\''),
        make_option('-b',
            '--'+util.BUILD,
            action='store',
            type='string',
            dest=util.BUILD,
            help='designate the build like \'04\' or \'16\''),
    )
    task = 'init_pkg_db'

    #clear all packages of corresponding os release in db
    def clear_build(self):
        os_release,created = OSRelease.objects.get_or_create(name=self.os_release_str)
        Package.objects.filter(os_release=os_release).delete()

    def handle(self, *args, **options):
        self.os_release_str = options[util.OS_RELEASE]
        self.build = options[util.BUILD]
        if not self.os_release_str or not self.build:
            sys.stderr.write('build or os_release option not given\n')
            util.halt(self.task)
        init_source_file = util.pkg_list_file.format(self.os_release_str, self.build)
        if not os.path.isfile(init_source_file):
            sys.stderr.write('Error: {0} build {1} package list does not exists\n'.format(self.os_release_str, self.build))
            util.halt(self.task)
        self.clear_build()
        init_log = util.read_file(init_source_file)
        for line in init_log.split('\n'):
            if util.CATEGORY in line: #if it has category indicates it is a working package not obsoleted or renamed
                pkg_info_dict = util.get_dict_from_line(line)
                #change flag 'n' to 'i', n->normal, i->initial
                if 'n' == pkg_info_dict[util.FLAG]:
                    pkg_info_dict[util.FLAG] = 'i'
                else:
                    util.error_log(
                        self.task, 'package flag error: flag \'{0}\' supposed to be \'n\''.format(flag_str),
                        util.pkg_log_info.format(pkg_name, self.os_release_str, self.build)
                    )
                #create the package
                util.create_package(self.task, pkg_info_dict, self.os_release_str, self.build)
        util.log(self.task, 'success')
